package com.shelpe.services.sinbadgateway.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Setter
public class AppTokenAuthenticationProvider implements AuthenticationProvider {

	private String appToken;
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		log.debug("convert to special oauth token: {}", authentication.getPrincipal());
		
		if(authentication.getCredentials() != null && authentication.getCredentials().equals(this.appToken)){
			AuthorizationRequest req = new AuthorizationRequest();
			req.setClientId(authentication.getPrincipal().toString());
			List<String> scopes = new ArrayList<String>();
			scopes.add("apptoken");
			req.setScope(scopes);
			OAuth2Authentication token = new OAuth2Authentication(req.createOAuth2Request(), authentication);
			return token;
		}else{
			throw new BadCredentialsException("app token is invalid");
		}
		
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return TestingAuthenticationToken.class.isAssignableFrom(authentication);
	}

}
